package com.dai.zhenfujin.visitingcard.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProInfoBean;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.UserBean;
import com.dai.zhenfujin.db.EaseConstant;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.message.ChatActivity;
import com.dai.zhenfujin.my.bean.MyBean;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.ShowImagesDialog;
import com.dai.zhenfujin.visitingcard.app.adapter.PersonalDetailsListviewAdapter2;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 个人详情
 */
public class PersonalDetailsActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvTitleName, pp_adapter_name, pp_adapter_position, pp_adapter_bloc, item_word_type, tv_info, pp_adapter_company, tv_price,item_word_job,tv_biaoti;
    private FrameLayout imageView;
    private RecyclerView recyclerView;
    private ListView listView;
    private TextView attention, pdh_signature, tv_address;

    private List<MyBean> beans;
    private PersonalDetailsListviewAdapter2 adapter;
    private Button btMessage, btColleague;
    private int page = 1;
    private int number = 10;
    private String user_id;
    private List<ProListBean.ProListBean2> proListBean = new ArrayList<>();
    private View headview;
    private CircleImageView cv_img;
    private RelativeLayout rl_lahei,rl_yenzhen;
    private Switch switch_lahei;
    private ProListBean.ProListBean2 proListBean1;
    private String user_mobile;
    private String pro_id;
    private Banner banner;
    private ImageView iv_per,iv_qiye;
    private LinearLayout ll_msg;
    private RecyclerView pp_recyclerview;
    private String user_logo;
    private ArrayList<String> list_path = new ArrayList<>();
    private SmartRefreshLayout refreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_details);
        headview = LayoutInflater.from(this).inflate(R.layout.personal_details_head, null);
        proListBean1 = (ProListBean.ProListBean2) getIntent().getSerializableExtra("proListBean");
        initView();

        initRefresh();
        getProductInfo();
    }



    private void initRefresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getProductList(true);
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();
                    }
                },1500);
            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getProductList(false);
            }
        });
    }

    private void onRefresh() {
        page = 1;
        getProductList(true);
    }


    private void initView() {
        user_id = getIntent().getStringExtra("user_id");
        int type = getIntent().getIntExtra("type",0);

        tvTitleName = (TextView) findViewById(R.id.title_textview);
        tvTitleName.setText("TA的详情");
        imageView = findViewById(R.id.fl_img);
        btColleague = findViewById(R.id.pd_colleague);
        btMessage = findViewById(R.id.pd_message);
        ll_msg = findViewById(R.id.ll_msg);
      //  pp_recyclerview = findViewById(R.id.pp_recyclerview);
        refreshLayout = findViewById(com.dai.zhenfujin.R.id.refreshLayout);
        //轮播图
        banner = headview.findViewById(R.id.pp_adapter_imageview);
        pp_adapter_name = headview.findViewById(R.id.pp_adapter_name); //
        pp_adapter_position = headview.findViewById(R.id.pp_adapter_position); //
        pp_adapter_bloc = headview.findViewById(R.id.pp_adapter_bloc); // 集团
        item_word_type = headview.findViewById(R.id.item_word_type); //
        pp_adapter_company = headview.findViewById(R.id.pp_adapter_company); //
        tv_price = headview.findViewById(R.id.tv_price); //
        pdh_signature = headview.findViewById(R.id.pdh_signature); // 个性签名
        cv_img = headview.findViewById(R.id.cv_img); //
        tv_info = headview.findViewById(R.id.tv_info); //
        attention = headview.findViewById(R.id.attention); // 关注
        tv_address = headview.findViewById(R.id.tv_address); // 地址
        switch_lahei = headview.findViewById(R.id.switch_lahei); //
        rl_lahei = headview.findViewById(R.id.rl_lahei); //拉黑
        rl_yenzhen = headview.findViewById(R.id.rl_yenzhen); //认证
        iv_per = headview.findViewById(R.id.iv_per); // 个人认证
        iv_qiye = headview.findViewById(R.id.iv_qiye); //企业认证
        item_word_job = headview.findViewById(R.id.item_word_job);
        tv_biaoti = headview.findViewById(R.id.tv_biaoti);
        rl_yenzhen.setVisibility(View.VISIBLE);
        item_word_job.setVisibility(View.GONE);
        tv_biaoti.setVisibility(View.GONE);


        listView = findViewById(R.id.personal_details_rv);
        imageView.setOnClickListener(this);
        btColleague.setOnClickListener(this);
        btMessage.setOnClickListener(this);
        attention.setOnClickListener(this);

        pro_id = getIntent().getStringExtra("pro_id");
        adapter = new PersonalDetailsListviewAdapter2(this, proListBean);
        listView.addHeaderView(headview);
        listView.setAdapter(adapter);

        //从粉丝列表过来的
        if (type == 1){
            rl_lahei.setVisibility(View.VISIBLE); //拉黑
            rl_yenzhen.setVisibility(View.VISIBLE); //认证
        }else {
            rl_lahei.setVisibility(View.GONE); //拉黑
           // rl_yenzhen.setVisibility(View.GONE); //认证
        }


        cv_img.setOnClickListener(v -> {
            list_path.clear();
            list_path.add(user_logo);
            ShowImagesDialog showImagesDialog = new ShowImagesDialog(this,list_path,0);
            showImagesDialog.show();
        });
        //监听
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (position > 0)
            startActivity(new Intent(PersonalDetailsActivity.this, ParticularsPageActivity.class)
                    .putExtra("pro_id", proListBean.get(position-1).getPro_id())
                    .putExtra("type_id", proListBean.get(position-1).type_id));
        });

        switch_lahei.setChecked(SPUtils.getBlackId(PersonalDetailsActivity.this,user_id));
        if (SPUtils.getBlackId(PersonalDetailsActivity.this,user_id)){
        }


        switch_lahei.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                addBlack();
            }else {
                removeBlack();
            }
        });
    }


    /**
     * 加入黑名单
     */
    private void addBlack() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("friend_id", user_id);
        params2.put("type", 1 + "");
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.BLACK, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) throws HyphenateException {
                EMClient.getInstance().contactManager().addUserToBlackList(user_id,true);
                SPUtils.saveBlackId(PersonalDetailsActivity.this,user_id,true);
            }
        });
    }

    /**
     * 移除黑名单
     */
    private void removeBlack() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("friend_id", user_id);
        params2.put("type", 2 + "");
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.BLACK, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) throws HyphenateException {
                EMClient.getInstance().contactManager().removeUserFromBlackList(user_id);
                SPUtils.saveBlackId(PersonalDetailsActivity.this,user_id,false);
            }
        });
    }

    private void getProductList(boolean isRefresh) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("user_id", user_id);
        params2.put("page", page + "");
        params2.put("number", number + "");
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.OPERPRODUCTLIST, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) {
                if (isRefresh) {
                    proListBean.clear();
                    page = 2;
                } else {
                    page++;
                    refreshLayout.finishLoadmore();
                }
                if (resultBean.pro_list.size() > 0) {
                    proListBean.addAll(resultBean.pro_list);
                    adapter.notifyDataSetChanged();
                } else {
                    refreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                }
            }
        });
    }


    private void getProductInfo() {
        Map<String, Object> params3 = new HashMap<>();
        Map<String, String> params4 = new HashMap<>();
        params4.put("user_id", user_id);
        //  params4.put("loc_x", SPUtils.getString(this, "longitude"));
        //  params4.put("loc_y", SPUtils.getString(this, "latitude"));
        params3.put("req_bd", params4);
        HttpClient.post(this, Constants.QUERYUSERINFO, params3, new CallBack<UserBean>() {
            @Override
            public void onSuccess(UserBean proInfoBean) {
                if (proInfoBean.state.equals("1")){  //审核过了
                    //在让展示
                    onRefresh();
                    pp_adapter_name.setText(proInfoBean.getUser_name());
                    pp_adapter_position.setText(proInfoBean.getUser_duties());
                    pp_adapter_bloc.setText("公司:" + proInfoBean.getUser_company()); //公司
                    // item_word_type.setBackgroundColor(getResources().getColor(R.color.white));
                    item_word_type.setText("主业:" + proInfoBean.getUser_job()); //描述  主业-副业

                    // tvAddress.setText(proInfoBean.getPro_info().getPro_address());
                    tv_info.setText("个性签名");
                    pdh_signature.setText(proInfoBean.getUser_desc()); //介绍 个性签名
                    //     tv_price.setText("￥" + proInfoBean.getPro_price() + "元");
                    tv_address.setText(proInfoBean.getUser_region() + " " + proInfoBean.getUser_address()); //地址
                    pp_adapter_company.setText(proInfoBean.getUser_company());
                    pp_adapter_company.setVisibility(View.GONE);
                    tv_price.setVisibility(View.GONE);
                    banner.setVisibility(View.GONE);
                    user_logo = proInfoBean.getUser_logo();
                    Glide.with(PersonalDetailsActivity.this).load(proInfoBean.getUser_logo()).into(cv_img);

                    if (proInfoBean.isfriend.equals("0")) {
                        attention.setText("未关注");
                    } else {
                        attention.setText("已关注");
                    }

                    if (proInfoBean.getAuth_com().equals("1")){ //公司认证 1已认征  2未认证
                        iv_qiye.setImageDrawable(getResources().getDrawable(R.mipmap.qiye));
                    }else {
                        iv_qiye.setImageDrawable(getResources().getDrawable(R.mipmap.qiye_no));
                    }

                    if (proInfoBean.getAuth_per().equals("1")){ //公司认证 1已认征  2未认证
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.per));
                    }else {
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.per_no));
                    }

                    user_mobile = proInfoBean.user_mobile;
                    //保存用户信息
                    SPUtils.saveConversionHeadPhoto(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_logo());
                    SPUtils.saveConversionNickName(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_name());
                    SPUtils.saveConversionJob(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_job());

                    if (user_mobile.equals(SPUtils.getString(PersonalDetailsActivity.this, Constants.USER_MOBILE))) {
                        // rl_lahei.setVisibility(View.GONE); //拉黑
                        attention.setVisibility(View.GONE); //关注
                        ll_msg.setVisibility(View.GONE);
                    }
                }else {
                    pp_adapter_name.setText(proInfoBean.getUser_name());
                    pp_adapter_bloc.setVisibility(View.GONE);
                    item_word_type.setVisibility(View.GONE);
                    // item_word_type.setBackgroundColor(getResources().getColor(R.color.white));
                    // tvAddress.setText(proInfoBean.getPro_info().getPro_address());
                    tv_info.setText("个性签名");
                    pdh_signature.setText("暂无个性签名"); //介绍 个性签名
                    //     tv_price.setText("￥" + proInfoBean.getPro_price() + "元");
                    tv_address.setText("暂无地址"); //地址
                   // pp_adapter_company.setText(proInfoBean.getUser_company());
                    pp_adapter_company.setVisibility(View.GONE);
                    tv_price.setVisibility(View.GONE);
                    banner.setVisibility(View.GONE);
                    user_logo = proInfoBean.getUser_logo();
                    Glide.with(PersonalDetailsActivity.this).load(proInfoBean.getUser_logo()).into(cv_img);


                    if (proInfoBean.getAuth_com().equals("1")){ //公司认证 1已认征  2未认证
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.qiye));
                    }else {
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.qiye_no));
                    }

                    if (proInfoBean.getAuth_per().equals("1")){ //公司认证 1已认征  2未认证
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.per));
                    }else {
                        iv_per.setImageDrawable(getResources().getDrawable(R.mipmap.per_no));
                    }

                    user_mobile = proInfoBean.user_mobile;
                    //保存用户信息
                    SPUtils.saveConversionHeadPhoto(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_logo());
                    SPUtils.saveConversionNickName(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_name());
                 //   SPUtils.saveConversionJob(PersonalDetailsActivity.this, user_mobile, proInfoBean.getUser_job());

                    if (user_mobile.equals(SPUtils.getString(PersonalDetailsActivity.this, Constants.USER_MOBILE))) {
                        // rl_lahei.setVisibility(View.GONE); //拉黑
                        attention.setVisibility(View.GONE); //关注
                        ll_msg.setVisibility(View.GONE);
                    }

                    ll_msg.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_img:
                finish();
                break;
            case R.id.attention: //关注
                if (user_mobile.equals(SPUtils.getString(PersonalDetailsActivity.this, Constants.USER_MOBILE))) {
                    UIUtils.showToastSafe("自己不能关注自己");
                    return;
                }
                follow();
                break;
            case R.id.pd_colleague://同事
                Intent intent = new Intent(this, ColleagueActivity.class);
                intent.putExtra("company_name",pp_adapter_bloc.getText().toString().trim());
                intent.putExtra("user_id",user_id);
                startActivity(intent);
                break;
            case R.id.pd_message://发消息
                SPUtils.saveConversionPorId(this, user_mobile, pro_id);  //手机号码
                SPUtils.saveConversionUserId(this, user_mobile, user_id);
                SPUtils.saveSendMsg(this, user_mobile, true);
                if (user_mobile.equals(SPUtils.getString(PersonalDetailsActivity.this, Constants.USER_MOBILE))) {
                    UIUtils.showToastSafe("自己不能和自己聊天");
                    return;
                }
                startActivity(new Intent(PersonalDetailsActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, user_mobile));
                break;
        }
    }

    private void follow() {
        int type2;
        if (attention.getText().toString().trim().equals("未关注")) {
            type2 = 1;
        } else {
            type2 = 2;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> params2 = new HashMap<>();
        params2.put("friend_id", user_id);
        params2.put("type", type2);
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.FOLLOW, params, new CallBack<ProInfoBean>() {
            @Override
            public void onSuccess(ProInfoBean proInfoBean) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.UPDATA_FOLLOW_LIST);
                EventBus.getDefault().post(messageEvent);

                if (attention.getText().toString().equals("未关注")) {
                    attention.setText("已关注");
                } else {
                    attention.setText("未关注");
                }
            }
        });
    }
}
